package com.code.soulquartz.schedule;

import com.code.soulquartz.job.TestJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lyf
 * @date 2022-09-19-09:59
 */
@Configuration
public class ScheduleConfiguration {

    @Bean
    public JobDetail jobDetail() {
        return JobBuilder.newJob(TestJob.class)
                .withIdentity("job1")
                .storeDurably()
                .build();
    }

    @Bean
    public Trigger trigger() {
        // 如果需要在整秒且10分钟执行一次，可以直接利用cron表达式实现
        // 对应的表达式：0 0,10,20,30,40,50 * * * ? *    在整秒(0s)执行且每隔10分钟执行一次

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Calendar nowTime = Calendar.getInstance();
        // nowTime.add(Calendar.SECOND, 20);
        // 未来的某个时间点开始执行
        Date date = DateBuilder.futureDate(20, DateBuilder.IntervalUnit.SECOND);
        System.out.println("start ... " + sdf.format(date));
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail())
                .withIdentity("trigger")
                .startAt(date)
                .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ? *"))
                // .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(5))
                .build();
    }
}
